package com.yc.autouser.filter;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yc.autouser.entity.vo.LoginUserVo;
import com.yc.common.expection.BusinessException;
import com.yc.common.utils.JwtUtils;
import com.yc.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtils redisUtils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从请求头获取token
        String token=request.getHeader("token");
        if (!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //解析token,格式:{iss=yc, exp=1659531309, iat=1659444909, jti=d36ef58b-1aa4-46c2-ab2e-8d2ba65e6b9c, username=jiesen}
       String username=null;
        try {
            JSONObject tokenMessage= JSONUtil.parseObj(JwtUtils.parseToken(token).getSubject());
             username=tokenMessage.getStr("username");
        } catch (Exception e) {
            throw new BusinessException("token非法");
        }
        //redis中获取用户信息
        LoginUserVo loginUserVo = (LoginUserVo) redisUtils.get("login" + username);
        if (Objects.isNull(loginUserVo)){
            throw new BusinessException("用户未登录");
        }

        //用三个参数构造得方法才是已认证状态,第三个参数为权限信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=
                new UsernamePasswordAuthenticationToken(loginUserVo,null,null);
        //存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //放行
        filterChain.doFilter(request,response);


    }
}
